// 好友模块路由处理函数

// 引入jwt
const jwt = require('jsonwebtoken')
const secretKey = 'ethink'    // 密钥
const utils = require("../common/utils")
const server = require("../server/friend")
const mServer = require("../server/message")

// 发送好友请求
exports.friendRequest = (req, res) => {
  let friend_id = req.query.id
  let token = req.get('Authorization').split(' ')[1]
  let id = jwt.verify(token, secretKey).id
  server.friendRequest(id, friend_id).then(result => {
    if (result == '添加成功,已成为好友') {
      // 获取好友请求招呼语句
      mServer.getHelloFromFriend(id, friend_id).then(data => {
        return res.send({
          code: 200,
          message: result,
          data
        })
      }).catch(e => {
        return res.cc(e)
      })
    } else {
      return res.cc(result, 200)
    }
  }).catch(e => {
    return res.cc(e)
  })
}

// 拒绝好友请求
exports.rejectFriend = (req, res) => {
  let friend_id = req.query.id
  let token = req.get('Authorization').split(' ')[1]
  let id = jwt.verify(token, secretKey).id 
  server.rejectFriend(id, friend_id).then(result => {
    return res.cc(result, 200)
  }).catch(e => {
    return res.cc(e)
  })
}

// 同意好友请求
exports.beFriend = (req, res) => {
  let friend_id = req.body.id
  let token = req.get('Authorization').split(' ')[1]
  let id = jwt.verify(token, secretKey).id 
  server.beFriend(id, friend_id).then(result => {
    // 获取好友请求招呼语句
    mServer.getHelloFromFriend(id, friend_id).then(data => {
      return res.send({
        code: 200,
        message: result,
        data
      })
    }).catch(e => {
      return res.cc(e)
    })
  }).catch(e => {
    return res.cc(e)
  })
}

// 删除好友
exports.deleteFriend = (req, res) => {
  let friend_id = req.query.id
  let token = req.get('Authorization').split(' ')[1]
  let id = jwt.verify(token, secretKey).id 
  server.deleteFriend(id, friend_id).then(result => {
    return res.cc(result, 200)
  }).catch(e => {
    return res.cc(e)
  })
}